//
//  TTIChannelVC.m
//  ContentApp
//
//  Created by Jery on 2018/7/17.
//  Copyright © 2018年 翔傲科技. All rights reserved.
//

#import "TTIChannelVC.h"
#import "MyChannelCollectionViewCell.h"
#import "MoreChannelCollectionViewCell.h"

#define margin              5
#define CollectionCellWidth (UIScreenWidth-60)/3

@interface TTIChannelVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    
}
@property (weak, nonatomic) IBOutlet UICollectionView *MyChannelView;//我的频道CollectionView
@property (weak, nonatomic) IBOutlet UICollectionView *MoreChannelView;//更多频道CollectionView
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *MyChannelView_Height;//我的频道CollectionView高度，默认110
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *MoreChannelView_Height;//更多频道CollectionView高度，默认110


@property (nonatomic ,strong)NSMutableArray     *MyChannelArr;//我的频道数组
@property (nonatomic ,strong)NSMutableArray     *MoreChannelArr;//更多频道数组
@property (nonatomic ,strong)UIButton           *EditBtn;//编辑按钮
@end

@implementation TTIChannelVC

#pragma mark ---------------------------- 初始化事件 --------------------------
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NAV_INIT(self, @"频道", nil, nil, nil, nil);
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self initButton];
    [self InitCollectionView];
    
    [self getData];
    // Do any additional setup after loading the view.
}

#pragma mark --- 导航栏编辑按钮初始化
- (void)initButton
{
    _EditBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [_EditBtn setTitle:@"编辑" forState:0];
    [_EditBtn setTitle:@"完成" forState:UIControlStateSelected];
    [_EditBtn setTitleColor:[UIColor redColor] forState:0];
    [_EditBtn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    [_EditBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [_EditBtn addTarget:self action:@selector(EditAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_EditBtn];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
}

#pragma mark --- 频道CollectionView初始化
- (void)InitCollectionView
{
    // collection
    _MyChannelView.dataSource = self;
    _MyChannelView.delegate = self;
    _MyChannelView.scrollEnabled = NO;
    _MyChannelView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _MyChannelView.backgroundColor = [UIColor whiteColor];
    
    // 注册自定义 cell
    [_MyChannelView registerNib:[UINib nibWithNibName:NSStringFromClass([MyChannelCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"MyChannelCollectionViewCell"];
    
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    [_MyChannelView addGestureRecognizer:longPressGesture];

    
    // collection
    _MoreChannelView.dataSource = self;
    _MoreChannelView.delegate = self;
    _MoreChannelView.scrollEnabled = NO;
    _MoreChannelView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _MoreChannelView.backgroundColor = [UIColor whiteColor];
    
    // 注册自定义 cell
    [_MoreChannelView registerNib:[UINib nibWithNibName:NSStringFromClass([MoreChannelCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"MoreChannelCollectionViewCell"];
}

#pragma mark --- 获取用户的频道数据
- (void)getData
{
    NSArray *arrtest1 = [NSArray arrayWithObjects:@"纽崔莱",@"XS",@"雅姿",@"家居科技",@"个人护理",@"海外购",@"美好生活",@"海外购海外购", nil];
    [self.MyChannelArr addObjectsFromArray:arrtest1];
    
    NSArray *arrtest2 = [NSArray arrayWithObjects:@"海外购",@"美好生活",@"海外购海外购", nil];
    [self.MoreChannelArr addObjectsFromArray:arrtest2];
    
    [self Update_CollectionViewHeigth];
     
    [self.MyChannelView reloadData];
    [self.MoreChannelView reloadData];
}

#pragma mark ---------------------------- 响应事件 --------------------------
#pragma mark --- 编辑事件
- (void)EditAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        //编辑
        [self.MyChannelView reloadData];
        [self.MoreChannelView reloadData];
    }
    else
    {
        //完成
        [self.MyChannelView reloadData];
        [self.MoreChannelView reloadData];
    }

}

#pragma mark --- CollectionView视图高度更新事件
- (void)Update_CollectionViewHeigth
{
    //大于3行,更新视图高度
    //高度大于110,更新视图高度
    if (_MyChannelArr.count>9 || _MyChannelView_Height.constant >110)
    {
        int more =  _MyChannelArr.count%3;
        long line = (_MyChannelArr.count - more)/3;
        if (more != 0)
            line = line + 1;
        
        _MyChannelView_Height.constant = line*30 + (line - 1)*10;
    }
    
    //大于3行,更新视图高度
    //高度大于110,更新视图高度
    if (_MoreChannelArr.count>9 || _MoreChannelView_Height.constant >110)
    {
        int more =  _MoreChannelArr.count%3;
        long line = (_MoreChannelArr.count - more)/3;
        if (more != 0)
            line = line + 1;
        
        _MoreChannelView_Height.constant = line*30 + (line - 1)*10;
    }
}

#pragma mark --- 移动频道cell事件
- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    //获取此次点击的坐标，根据坐标获取cell对应的indexPath
    CGPoint point = [longPress locationInView:_MyChannelView];
    NSIndexPath *indexPath = [self.MyChannelView indexPathForItemAtPoint:point];
    //根据长按手势的状态进行处理。
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            //当没有点击到cell的时候不进行处理
            if (!indexPath) {
                break;
            }
            //开始移动
            [_MyChannelView beginInteractiveMovementForItemAtIndexPath:indexPath];
            break;
        case UIGestureRecognizerStateChanged:
            //移动过程中更新位置坐标
            [_MyChannelView updateInteractiveMovementTargetPosition:point];
            break;
        case UIGestureRecognizerStateEnded:
            //停止移动调用此方法
            [_MyChannelView endInteractiveMovement];
            break;
        default:
            //取消移动
            [_MyChannelView cancelInteractiveMovement];
            break;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---------------------------- 懒加载 --------------------------
- (NSMutableArray *)MyChannelArr
{
    if (!_MyChannelArr) {
        _MyChannelArr = [NSMutableArray array];
    }
    return _MyChannelArr;
}

- (NSMutableArray *)MoreChannelArr
{
    if (!_MoreChannelArr) {
        _MoreChannelArr = [NSMutableArray array];
    }
    return _MoreChannelArr;
}

#pragma mark ---------------------------- 代理事件 --------------------------
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (!_EditBtn.selected) {
        return;
    }
    
    if (collectionView == _MyChannelView) {
        
        if (_MyChannelArr.count >indexPath.row)
        {
            [_MoreChannelArr addObject:[_MyChannelArr objectAtIndex:indexPath.row]];
            [_MyChannelArr removeObjectAtIndex:indexPath.row];
            
            [self Update_CollectionViewHeigth];
            [self.MyChannelView reloadData];
            [self.MoreChannelView reloadData];
        }
    }
    else
    {
        if (_MoreChannelArr.count >indexPath.row)
        {
            [_MyChannelArr addObject:[_MoreChannelArr objectAtIndex:indexPath.row]];
            [_MoreChannelArr removeObjectAtIndex:indexPath.row];
            
            [self Update_CollectionViewHeigth];
            [self.MyChannelView reloadData];
            [self.MoreChannelView reloadData];
        }
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == _MyChannelView) {
        return _MyChannelArr.count;
    }
    else
    {
        return _MoreChannelArr.count;
    }
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _MyChannelView) {
        MyChannelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyChannelCollectionViewCell" forIndexPath:indexPath];
        
        if (_MyChannelArr.count>indexPath.row)
        {
            NSString *title = [_MyChannelArr objectAtIndex:indexPath.row];
            cell.title.text = title;
            if (_EditBtn.selected)
                cell.DeleteImg.hidden = NO;
            else
                cell.DeleteImg.hidden = YES;
        }
        return cell;
    }
    else
    {
        MoreChannelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MoreChannelCollectionViewCell" forIndexPath:indexPath];
        
        if (_MoreChannelArr.count>indexPath.row)
        {
            NSString *title = [_MoreChannelArr objectAtIndex:indexPath.row];
            cell.title.text = title;
            if (_EditBtn.selected)
                cell.AddImg.hidden = NO;
            else
                cell.AddImg.hidden = YES;
        }
        return cell;
    }
    
}


/** 每个cell的尺寸*/
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(CollectionCellWidth, 30);//根据屏幕算出尺寸
}

#pragma mark - UICollectionViewDelegateFlowLayout
/** section的margin*/
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    
    return UIEdgeInsetsMake(0, 20, 0,20);//根据屏幕算出间距
}


// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return margin;
}

// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

//根据indexpath判断单元格是否可以移动，如果都可以移动，直接就返回YES ,不能移动的返回NO
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {

    if (_EditBtn.selected)//非编辑状态不可移动
        return YES;
    else
        return NO;
}

/**
 *sourceIndexPath 原始数据 indexpath
 * destinationIndexPath 移动到目标数据的 indexPath
 */
// 在移动结束的时候调用此代理方法
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    
    NSString *str1 = _MyChannelArr[sourceIndexPath.row];//先取出需要移动的对象
    [_MyChannelArr removeObjectAtIndex:sourceIndexPath.row];//删除数组中该对象
    [_MyChannelArr insertObject:str1 atIndex:destinationIndexPath.row];//将该对象置入数组目标位置
}

@end
